<?

function _wiki_page($link) {
	global $db;
	
	$id = $_REQUEST["id"];
	
	$type = "page";
	if (preg_match("/(\.jpg|\.gif|\.png)$/",$link)) $type = "image";
	#if (preg_match("/(\.zip|\.gz|\.tgz)$/",$link)) $type = "data";
	#if (preg_match("/(\.py|\.php|\.c)$/",$link)) $type = "code";
	
	if ($id) {
	$e = $db->query1("select * from wiki where ".
		" link = ".$db->sqlstring($link).
		" and id = ".$db->sqlint($id).
		" limit 1");
	} else {
	$e = $db->query1("select * from wiki where ".
		" link = ".$db->sqlstring($link).
		" and latest = 1 ".
		" limit 1");
	}
	$e["link"] = $link;
	$e["type"] = $type;
	if (!$e["id"]) {
		$e["name"] = $e["link"];
		$e["title"] = $e["link"];
		}
	if ($_REQUEST["parent"]) $_SESSION["wiki_parent"] = $_REQUEST["parent"];

	return $e;
	}
	
function _wiki_latest($link,$id) {
	global $db;
	$db->query0("update wiki set latest = (id = ".$db->sqlint($id).") where link = ".$db->sqlstring($link));
	}

	
function _wiki_insert($e) {
	global $db,$user;
	$link = $e["link"];
	$oe = $db->query1("select * from wiki where ".
		" link = ".$db->sqlstring($link).
		" and latest = 1 ".
		" limit 1");
	$diff = 0;
	foreach ($e as $k=>$v) {
		if ($e[$k] != $oe[$k]) $diff++;
		}
	if (!$diff) return;
	
	$e = array_merge($oe,$e);
	
	if (!$e["name"]) $e["name"] = $e["link"];
	if (!$e["title"]) $e["title"] = $e["link"];
	if (!$oe["id"]) $e["parent"] = $_SESSION["wiki_parent"];
	$e["datetimeon"]=date("Y-m-d H:i:s");
	$e["users_id"]=$user["id"];
	$id = $db->autoquery("insert","wiki",$e);
	_wiki_latest($link,$id);
	return $id;
	}
	
function _wiki_getsection($content,$section) {
	$section = preg_quote($section,"/");
	if (preg_match('/\<(h\d)\>('.$section.')\<\/\1>(.+?)((<h\d\>)|($))/is',$content,$m)) {
		return $m[3];
		}
	}
	
function _wiki_setsection($content,$section,$value) {
	}
	
$link = $_REQUEST["link"];
if ($v = $params["fname"]) $link = $v;

if (!preg_match("/^[a-zA-Z0-9_\-\.]+$/",$link)) { fusedie("Invalid link.  Links must match the pattern /^[a-zA-Z0-9_\-\.]+$/"); }

$e = _wiki_page($link);
skin_param("wiki",$e);
return $e;
?>